package com.shpng.cheapenglish.action;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shpng.cheapenglish.entity.SUser;
import com.shpng.cheapenglish.entity.SUserWord;
import com.shpng.cheapenglish.entity.SWord;
import com.shpng.cheapenglish.manager.UserManager;
import com.shpng.cheapenglish.manager.WordManager;

public class WordRecordAction {

	private long wordId;

	private int degree;

	// 记录单词，并返回新单词
	@SuppressWarnings("unchecked")
	public String execute(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String email = (String) req.getSession().getAttribute("email");
		UserManager userManager = UserManager.getInstance();
		SUser user = userManager.getUser(email);
		WordManager wordManager = WordManager.getInstance();
		if (wordId > 0) {
			SUserWord uw = wordManager.getUserWord(user, wordId);

			if (uw != null) {
				uw.setAverageDegree((uw.getAverageDegree()
						* uw.getReciteTimes() + degree)
						/ (uw.getReciteTimes() + 1));
				uw.setReciteTimes(uw.getReciteTimes() + 1);
				try {
					wordManager.saveOrUpdateUserWord(uw.getDbUserWord());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		List<Long> wordIds = (List<Long>) req.getSession().getAttribute(
				"wordIds");
		if (wordIds == null) {
			resp.getWriter().println("{error:'出错了'}");
		} else if (wordIds.size() <= 0) {
			resp.getWriter().println("{message:'单词背完了'}");
		} else {
			Iterator<Long> iterator = wordIds.iterator();
			if (iterator.hasNext()) {
				Long wordId = iterator.next();
				iterator.remove();
				SWord word = wordManager.getWord(wordId);
				resp.setContentType("text/xml;charset=utf-8");
				resp.getWriter().print(word.toJsonString());
				req.getSession().setAttribute("wordIds", wordIds);
			}
		}
		return null;
	}

	public long getWordId() {
		return wordId;
	}

	public void setWordId(long wordId) {
		this.wordId = wordId;
	}

	public int getDegree() {
		return degree;
	}

	public void setDegree(int degree) {
		this.degree = degree;
	}

}
